<template>
  <div class="vod-player-example">
    <h2>华为云VOD播放器示例</h2>


    <!-- 文件上传区域 -->
    <div class="upload-section">
      <h3>文件上传</h3>
      <div class="form-group">
        <label>选择视频文件:</label>
        <input type="file" @change="handleFileSelect" accept="video/*,audio/*" class="file-input" />
      </div>
      <div v-if="selectedFile" class="file-info">
        <p><strong>文件名:</strong> {{ selectedFile.name }}</p>
        <p><strong>文件大小:</strong> {{ formatFileSize(selectedFile.size) }}</p>
        <p><strong>文件类型:</strong> {{ selectedFile.type }}</p>
      </div>
      <div class="form-group">
        <label>媒资标题:</label>
        <input v-model="uploadParams.title" placeholder="输入视频标题" class="input" />
      </div>
      <div class="form-group">
        <label>媒资描述:</label>
        <textarea v-model="uploadParams.description" placeholder="输入视频描述（可选）" class="textarea" />
      </div>
      <div class="form-group">
        <label>分段大小 (MB):</label>
        <select v-model="chunkSizeMB" class="select">
          <option value="5">5MB</option>
          <option value="10">10MB</option>
          <option value="20">20MB</option>
        </select>
      </div>
      <div class="button-group">
        <button @click="handleDirectUpload"
          :disabled="!selectedFile || loading || uploadStatus.isUploading || selectedFile.size > 20 * 1024 * 1024"
          class="btn btn-info">
          {{ uploadStatus.isUploading ? '上传中...' : '直接上传 (<20MB)' }} </button>
            <button @click="handleChunkedUpload" :disabled="!selectedFile || loading || uploadStatus.isUploading"
              class="btn btn-success">
              {{ uploadStatus.isUploading ? '上传中...' : '分段上传' }}
            </button>
            <button @click="handleUploadAndPlay" :disabled="!selectedFile || loading || uploadStatus.isUploading"
              class="btn btn-primary">
              {{ uploadStatus.isUploading ? '上传中...' : '上传并播放' }}
            </button>
      </div>

      <!-- 上传进度 -->
      <div v-if="uploadStatus.isUploading" class="progress-section">
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: uploadStatus.progress + '%' }"></div>
        </div>
        <p class="progress-text">{{ uploadStatus.message }} ({{ uploadStatus.progress }}%)</p>
        <p class="chunk-info">分段进度: {{ uploadStatus.currentChunk }}/{{ uploadStatus.totalChunks }}</p>
      </div>
    </div>

    <!-- 直接播放已存在媒资 -->
    <div class="direct-play-section">
      <h3>播放已存在媒资</h3>
      <div class="form-group">
        <label>媒资ID:</label>
        <input v-model="assetId" type="text" placeholder="输入媒资ID" />
        <button @click="handleDirectPlay" :disabled="loading || !assetId" class="play-btn">
          获取播放地址
        </button>
      </div>
    </div>

    <!-- 错误信息 -->
    <div v-if="error" class="error-message">
      <p>❌ {{ error }}</p>
      <button @click="reset" class="reset-btn">重置</button>
    </div>

    <!-- 播放器 -->
    <div v-if="playInfo" class="player-section">
      <h3>视频播放</h3>

      <!-- 清晰度选择 -->
      <div class="quality-selector">
        <label>清晰度:</label>
        <select v-model="selectedQuality" @change="updatePlayUrl">
          <option value="">自动（最高清晰度）</option>
          <option v-for="url in playInfo.playUrls" :key="url.quality" :value="url.quality">
            {{ url.quality }} ({{ url.format }})
          </option>
        </select>
      </div>

      <!-- 视频播放器 -->
      <VideoPlayer ref="playerRef" :src="currentPlayUrl" :poster="playInfo.coverUrl" :width="800" :height="450" controls
        @play="onPlay" @pause="onPause" @ended="onEnded" @error="onPlayerError" @time-update="onTimeUpdate" />

      <!-- 播放信息 -->
      <div class="play-info">
        <p><strong>媒资ID:</strong> {{ playInfo.assetId }}</p>
        <p><strong>时长:</strong> {{ formatDuration(playInfo.duration) }}</p>
        <p><strong>播放地址数量:</strong> {{ playInfo.playUrls.length }}</p>
        <p><strong>当前播放时间:</strong> {{ formatDuration(currentTime) }} / {{ formatDuration(duration) }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useVodPlayer } from '../hooks/useVodPlayer'
import VideoPlayer from '../components/VideoPlayer.vue'
import type { ChunkedUploadParams, UploadProgress } from '../types/vod'

// 使用VOD播放器
const {
  loading,
  error: vodError,
  playInfo,
  uploadStatus,
  getPlayInfo,
  getBestPlayUrl,
  getPlayUrlByQuality,
  uploadByChunks,
  uploadAndGetPlayInfo,
  uploadDirect,
  reset
} = useVodPlayer()

// 本地错误状态
const error = ref('')


// 分段上传参数
const uploadParams = ref({
  title: '',
  description: '',
  categoryId: undefined as number | undefined,
  autoPublish: true,
  transcodeTemplateGroupName: 'system_template_group'
})

// 文件上传相关
const selectedFile = ref<File | null>(null)
const chunkSizeMB = ref(10)

// 标签输入
const tagsInput = ref('')

// 直接播放媒资ID
const assetId = ref('')

// 播放器相关
const playerRef = ref()
const selectedQuality = ref('')
const currentTime = ref(0)
const duration = ref(0)

// 当前播放URL
const currentPlayUrl = computed(() => {
  if (!playInfo.value) return ''

  if (selectedQuality.value) {
    return getPlayUrlByQuality(selectedQuality.value)
  }

  return getBestPlayUrl()
})


// 处理文件选择
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    selectedFile.value = file
    // 自动设置标题为文件名（去掉扩展名）
    if (!uploadParams.value.title) {
      uploadParams.value.title = file.name.replace(/\.[^/.]+$/, '')
    }
  }
}

// 处理直接上传
const handleDirectUpload = async () => {
  if (!selectedFile.value) {
    console.error('请先选择文件')
    return
  }

  if (selectedFile.value.size > 20 * 1024 * 1024) {
    console.error('文件大小超过20MB，请使用分段上传')
    return
  }

  try {
    const tags = tagsInput.value ? tagsInput.value.split(',').map(tag => tag.trim()).filter(Boolean) : undefined
    const params = {
      file: selectedFile.value,
      title: uploadParams.value.title,
      description: uploadParams.value.description,
      categoryId: uploadParams.value.categoryId,
      tags,
      autoPublish: uploadParams.value.autoPublish,
      transcodeTemplateGroupName: uploadParams.value.transcodeTemplateGroupName,
      onProgress: (progress: UploadProgress) => {
        console.log('上传进度:', progress)
      }
    }
    const result = await uploadDirect(params)
    console.log('直接上传成功:', result)
    // 上传成功后可以获取播放信息
    if (result.assetId) {
      await getPlayInfo(result.assetId)
    }
  } catch (err) {
    console.error('直接上传失败:', err)
  }
}

// 处理分段上传
const handleChunkedUpload = async () => {
  if (!selectedFile.value) {
    console.error('请先选择文件')
    return
  }

  try {
    const tags = tagsInput.value ? tagsInput.value.split(',').map(tag => tag.trim()).filter(Boolean) : undefined
    const params: ChunkedUploadParams = {
      file: selectedFile.value,
      title: uploadParams.value.title,
      description: uploadParams.value.description,
      categoryId: uploadParams.value.categoryId,
      autoPublish: uploadParams.value.autoPublish,
      chunkSize: chunkSizeMB.value * 1024 * 1024,
      onProgress: (progress) => {
        console.log('上传进度:', progress)
      }
    }
    const assetId = await uploadByChunks(params)
    console.log('分段上传成功，媒资ID:', assetId)

    // 自动获取播放信息
    await getPlayInfo(assetId)
    selectedQuality.value = '' // 重置清晰度选择
  } catch (err) {
    console.error('分段上传失败:', err)
  }
}

// 处理分段上传并播放
const handleUploadAndPlay = async () => {
  if (!selectedFile.value) {
    error.value = '请先选择文件'
    return
  }

  try {
    const tags = tagsInput.value ? tagsInput.value.split(',').map(tag => tag.trim()).filter(Boolean) : undefined
    const params: ChunkedUploadParams = {
      file: selectedFile.value,
      title: uploadParams.value.title,
      description: uploadParams.value.description,
      categoryId: uploadParams.value.categoryId,
      tags,
      autoPublish: uploadParams.value.autoPublish,
      chunkSize: chunkSizeMB.value * 1024 * 1024 // 转换为字节
    }

    // 一键上传并获取播放信息
    await uploadAndGetPlayInfo(params)
    selectedQuality.value = '' // 重置清晰度选择
    console.log('分段上传并获取播放信息成功')
  } catch (err) {
    console.error('分段上传并播放失败:', err)
  }
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'

  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 处理直接播放
const handleDirectPlay = async () => {
  try {
    await getPlayInfo(assetId.value)
    selectedQuality.value = '' // 重置清晰度选择
  } catch (err) {
    console.error('获取播放信息失败:', err)
  }
}

// 更新播放URL
const updatePlayUrl = () => {
  // 播放URL会通过computed自动更新
}

// 播放器事件处理
const onPlay = () => {
  console.log('视频开始播放')
}

const onPause = () => {
  console.log('视频暂停')
}

const onEnded = () => {
  console.log('视频播放结束')
}

const onPlayerError = (errorMessage: string) => {
  console.error('播放器错误:', errorMessage)
}

const onTimeUpdate = (current: number, total: number) => {
  currentTime.value = current
  duration.value = total
}

// 格式化时长
const formatDuration = (seconds?: number): string => {
  if (!seconds) return '00:00'

  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)

  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }

  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}
</script>

<style scoped>
.vod-player-example {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.upload-section,
.direct-play-section,
.player-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
}

.transfer-form {
  display: grid;
  gap: 15px;
}

.form-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.form-group label {
  min-width: 100px;
  font-weight: 500;
}

.form-group input,
.form-group textarea,
.form-group select {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  min-height: 60px;
  resize: vertical;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-success {
  background: #28a745;
  color: white;
}

.btn:hover {
  opacity: 0.9;
}

.btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.file-input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.file-info {
  margin-top: 10px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  font-size: 14px;
}

.chunk-info {
  margin-top: 5px;
  font-size: 14px;
  color: #666;
}

.select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
}

.input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-height: 60px;
  resize: vertical;
}

.transfer-btn,
.play-btn,
.reset-btn {
  padding: 10px 20px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.transfer-btn:hover,
.play-btn:hover {
  background: #0056b3;
}

.transfer-btn:disabled,
.play-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.reset-btn {
  background: #dc3545;
}

.reset-btn:hover {
  background: #c82333;
}

.progress-section {
  margin-top: 20px;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #007bff, #28a745);
  transition: width 0.3s ease;
}

.progress-text {
  margin-top: 10px;
  text-align: center;
  font-weight: 500;
}

.error-message {
  padding: 15px;
  background: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  color: #721c24;
  margin-bottom: 20px;
}

.quality-selector {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.play-info {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.play-info p {
  margin: 5px 0;
}

h2,
h3 {
  color: #333;
  margin-bottom: 15px;
}
</style>
